#ifdef _WIN32

#include "IWin32Error.h"
#include "Format.h"
#include "UnicodeString.h"
#include "Macros.h"
#include <Windows.h>
#include <boost/scope_exit.hpp>

namespace lhcutils
{

IWin32Error::IWin32Error() { }
IWin32Error::~IWin32Error() { }

StringPtr IWin32Error::MakeExceptionMessage(StringPtr nonSystemMessage, DWORD errorCode)
{
	return Format(UnicodeString("{0} {1}"), *nonSystemMessage, *GetErrorText(errorCode));
}

StringPtr IWin32Error::GetErrorText(DWORD errorCode)
{
	LPWSTR errorText;
	DWORD charsInMessageNotCountingNull = FormatMessageW(
		FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS,
		NULL,
		errorCode,
		0,
		reinterpret_cast<LPWSTR>(&errorText),
		0,
		NULL);

	if(charsInMessageNotCountingNull == 0)
	{
		return Format(UnicodeString("Something has gone terribly wrong! Could not get error text for error code {0}!"), *ToString(errorCode));
	}
	else
	{
		BOOST_SCOPE_EXIT( (&errorText) )
		{
			UNUSED HLOCAL ret = LocalFree(errorText);
		} BOOST_SCOPE_EXIT_END
		
		StringPtr errorString = winstr(errorText, charsInMessageNotCountingNull);
		return errorString;
	}
}

}

#endif

/*
 Copyright 2011 Greg Najda

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
